package com.sgb.kjwl.view.ui.activity.manage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityUploadPicVideoBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.manage.PromotionalAlbumEntity;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow2;
import com.sgb.kjwl.viewmodel.manage.UploadPicViedeoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 宣传相册的上传图片和视频
 */
public class UploadPicAndVideoActivity extends WebSiteBuildBaseActivity {

    @Inject
    UploadPicViedeoModel viewModel;

    private ActivityUploadPicVideoBinding binding;
    private String localVideoUrl = "";
    private String picUrl = "";
    private int siteType = 1; //网站类型  0-个人 1-企业 2-团队 默认为1
    private String videoId = "";
    //相册选择弹窗
    SelectAlbumPopWindow2 selectAlbumPopWindow;

    String mUpLoadType = "";//上传类型

    private static final String TYPE_UPLOAD_VR = "3";

    private PromotionalAlbumEntity mEntity;
    private static final String KEY_UPLOAD_TYPE = "key_UPLOAD_TYPE";
    private static final String KEY_ENTITY = "key_entity";

    public static void start(Context context, int siteType) {
        Intent intent = new Intent(context, UploadPicAndVideoActivity.class);
        intent.putExtra("siteType", siteType);
        context.startActivity(intent);
    }

    /**
     * vr全景 专用
     * @param context
     * @param siteType
     * @param mUpLoadType
     */
    public static void start(Activity context, int siteType, String mUpLoadType, int requestCode) {
        Intent intent = new Intent(context, UploadPicAndVideoActivity.class);
        intent.putExtra("siteType", siteType);
        intent.putExtra(KEY_UPLOAD_TYPE, mUpLoadType);
        context.startActivityForResult(intent, requestCode);
    }

    public static void start(Activity context, int siteType, String mUpLoadType, PromotionalAlbumEntity entity, int requestCode) {
        Intent intent = new Intent(context, UploadPicAndVideoActivity.class);
        intent.putExtra("siteType", siteType);
        intent.putExtra(KEY_UPLOAD_TYPE, mUpLoadType);
        intent.putExtra(KEY_ENTITY, entity);
        context.startActivityForResult(intent, requestCode);
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        resetVideoPic();
    }

    private void resetVideoPic() {
        if (!TextUtils.isEmpty(videoId) && !TextUtils.isEmpty(localVideoUrl)) {
            Glide.with(this)
                    .asBitmap()
                    .load(localVideoUrl)
                    .apply(new RequestOptions().placeholder(R.drawable.null_img_list))
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            binding.ivUpdataImage.setImageBitmap(resource);
                        }
                    });
        }
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(UploadPicAndVideoActivity.this, R.layout.activity_upload_pic_video);
        binding.setViewModel(viewModel);
        siteType = getIntent().getIntExtra("siteType", 1);
        mUpLoadType = getIntent().getStringExtra(KEY_UPLOAD_TYPE);
        mEntity = (PromotionalAlbumEntity) getIntent().getSerializableExtra(KEY_ENTITY);
        binding.include.rightView.setOnClickListener(this);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.titleView.setText(TYPE_UPLOAD_VR.equals(mUpLoadType) ? "上传内容" : "上传图片");
        binding.tvSubmit.setOnClickListener(this);
        binding.ivBg.setOnClickListener(this);
        binding.ivDelect.setOnClickListener(this);
        binding.tvItvType.setContent("图片/视频");
        binding.ivUpdataImage.setRoundCorner(SizeUtils.dp2px(2), SizeUtils.sp2px(2));
//        binding.tvItvType.setOnWholeItemClickListener(new ItemInputTextView.OnWholeItemClickListener() {
//            @Override
//            public void OnWholeItemClick(View view) {
//                viewModel.getUploadType();
//            }
//        });
        String text = "图片：照片大小不能超过3MB，支持格式bmp.jpg.jpeg\n.png视频大小：小于500MB\n" +
                "支持格式：mpeg.mpg.avi.rm.rmvb.mov.asf.wmn.flv.f4v.m kv.mp4.3gp.awv.swf";
        binding.tvBeizhu.setText(text);
        viewModel.getPic_video_paths().observe(this, s -> {
            picUrl = s;
            showAvatar(s);
        });
        viewModel.getMessage().observe(this, s -> {
            if (!TextUtils.isEmpty(s)) {
                MToast.showToast(getActivity(), s);
                mUpLoadType = "";
                setResult(RESULT_OK);
                finish();
                return;
            }
        });
        viewModel.upLoadTypes.observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntities) {
                showUpLoadTypes(pickSelectEntities);
            }
        });

        binding.tvItvLink.setVisibility(TYPE_UPLOAD_VR.equals(mUpLoadType) ? View.VISIBLE : View.GONE);
        binding.tvTitleUpload.setText(TYPE_UPLOAD_VR.equals(mUpLoadType) ? "上传封面" : "上传图片/视频");
        binding.tvItvType.setVisibility(View.GONE);
        if (mEntity != null){
            renderView(mEntity);
        }
    }

    //vr全景回显
    private void renderView(PromotionalAlbumEntity mEntity) {
        if (!TextUtils.isEmpty(mEntity.getUrl())){
            viewModel.getPic_video_paths().postValue(mEntity.getUrl());
        }
        binding.tvItvLink.setContent(mEntity.getVrUrl());
        binding.etTitle.setContent(mEntity.getName());
        binding.etBeizhu.setText(mEntity.getRemark());
    }

    //上传类型
    private void showUpLoadTypes(List<PickSelectEntity> list) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = list.get(options1).getProjectscale();
            binding.tvItvType.setContent(content);
            mUpLoadType = list.get(options1).getNo();
            binding.tvItvLink.setVisibility(mUpLoadType.equals(TYPE_UPLOAD_VR) ? View.VISIBLE : View.GONE);
            binding.tvTitleUpload.setText(mUpLoadType.equals(TYPE_UPLOAD_VR) ? "上传封面" : "上传图片/视频");
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setTitleText("请选择类型")
                .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main))
                .build();
        businessOption.setPicker(list);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_bg: //图片上传
                //closeKeybord();
                if (TYPE_UPLOAD_VR.equals(mUpLoadType)) {
                    pictureSelector(true, 500, 1);
                } else {
                    if (TextUtils.isEmpty(picUrl) && TextUtils.isEmpty(videoId)) {
                        if (selectAlbumPopWindow == null) {
                            initAlbumPop();
                        }
                        showAlbumPop();
                    }
                }
                break;
            case R.id.iv_delect: //清空图片
                localVideoUrl = "";
                videoId = "";
                picUrl = "";
                showAvatar("");
                break;
            case R.id.tv_submit:
                if (!ClickUtils.isDoubleClick()) {
                    Map<String, Object> map = saveOrUpData();
                    if (map == null) return;
                    viewModel.saveOrUpdate(map);
                }
                break;
        }
    }

    private Map<String, Object> saveOrUpData() {
        if (viewModel == null)
            return null;
        Map<String, Object> map = new HashMap<>();
        if (TextUtils.isEmpty(binding.tvItvType.getContent())) {
            MToast.showToast(getActivity(), "请选择类型");
            return null;
        }
        map.put("type", mUpLoadType);
        if (TextUtils.isEmpty(binding.etTitle.getContent())) {
            MToast.showToast(getActivity(), "请填写标题");
            return null;
        }
        map.put("name", binding.etTitle.getContent());
        if (TYPE_UPLOAD_VR.equals(mUpLoadType) && TextUtils.isEmpty(binding.tvItvLink.getContent())){
            MToast.showToast(getActivity(), "请输入链接地址");
            return null;
        }
        map.put("vrUrl", binding.tvItvLink.getContent());
        if (TextUtils.isEmpty(picUrl) && TextUtils.isEmpty(localVideoUrl)) {
            MToast.showToast(getActivity(), "请上传图片或视频");
            return null;
        }

        if (!TextUtils.isEmpty(picUrl)) {//图片
            map.put("type", TextUtils.isEmpty(mUpLoadType) ? "1" : mUpLoadType);
            //map.put("name", new File(picUrl).getName());
            map.put("url", picUrl);
        }

        if (!TextUtils.isEmpty(localVideoUrl)) {//视频
            map.put("type", "2");
            //map.put("name", new File(localVideoUrl).getName());
            map.put("url", videoId);
        }
        map.put("id", mEntity != null ? mEntity.getId() : "");
        map.put("remark", binding.etBeizhu.getText().toString().trim());
        map.put("siteType", siteType + "");
        map.put("uploadPictures", picUrl);//图片上传
        return map;
    }


    //展开popuwindw
    private void showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow.isShowing()) {
            //满足条件展示
            selectAlbumPopWindow.showDownPopwindow(binding.grayLayout, true);
        }
    }

    private void showAvatar(String avatar) {
        if (TextUtils.isEmpty(avatar)) {
            binding.ivBg.setVisibility(View.VISIBLE);
            binding.ivDelect.setVisibility(View.GONE);
            binding.ivPlayer.setVisibility(View.GONE);
            binding.ivUpdataImage.setVisibility(View.GONE);
        } else {
            binding.ivBg.setVisibility(View.GONE);
            binding.ivPlayer.setVisibility(View.GONE);
            binding.ivDelect.setVisibility(View.VISIBLE);
            binding.ivUpdataImage.setVisibility(View.VISIBLE);
            //Glide展示图片
            Glide.with(this)
                    //加载设置宽高限制
                    .load(avatar + "?x-oss-process=image/resize,m_fixed,h_100")
                    //显示圆图
//                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.ivUpdataImage);
        }
    }

    private void initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow2(this);
        }

        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 1) {
                    //打开相册
                    pictureSelector(true, 500, 1);
                } else {
                    viewModel.videoSelector(1, 336);
                }
            }
        });
    }

    // 图片结果回调
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(file);
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case 336:
                List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                if (selectList1 != null && !selectList1.isEmpty()){
                    localVideoUrl = selectList1.get(0).getRealPath();
                    viewModel.getVideoParamsSTS(localVideoUrl);
                }

                break;
        }
    }

    /*
     * 请求上传视频返回的数据
     * */
    public void uploadVideoResult(String videoId, UploadFileInfo info) {
        this.videoId = videoId;
        runOnUiThread(() -> {
            DialogHelper.dismissProgressDialog();
            if (!TextUtils.isEmpty(localVideoUrl)) {
                //截取视频第一帧图片
//                File videoImageFile = new File(localVideoUrl);
//                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//                mmr.setDataSource(String.valueOf(videoImageFile));
//                Bitmap video = mmr.getFrameAtTime();
//                binding.ivUpdataImage.setImageBitmap(video);
                Glide.with(this)
                        .asBitmap()
                        .load(localVideoUrl)
                        .apply(new RequestOptions().placeholder(R.drawable.null_img_list))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                binding.ivUpdataImage.setImageBitmap(resource);
                            }
                        });
                binding.ivBg.setVisibility(View.GONE);
                binding.ivUpdataImage.setVisibility(View.VISIBLE);
                binding.ivDelect.setVisibility(View.VISIBLE);
                binding.ivPlayer.setVisibility(View.VISIBLE);
                binding.ivPlayer.setOnClickListener(v -> {
                    List<VideoBean> videoBeanList = new ArrayList<>();
                    VideoBean videoBean = new VideoBean();
                    videoBean.setVideoId(videoId);
                    videoBean.setCoverURL(localVideoUrl);
                    videoBean.setCover("");
                    videoBeanList.add(videoBean);
                    Intent intent = new Intent(getActivity(), PlayListActivity.class);
                    intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) videoBeanList);
                    intent.putExtra(PlayListActivity.PSO, 0);
                    intent.putExtra(PlayListActivity.IS_ShOW_USER, false);
                    intent.putExtra(PlayListActivity.VIDEOTYPE, "website_video");
                    getActivity().startActivity(intent);
                });
            }
        });
    }
}
